package com.learning.servlet2x.filter.gzip;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: GzipFilter
 * Description: 压缩过滤器
 * Date: 2014-12-9 21:41 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class GzipFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 获取浏览器支持的压缩格式
        String acceptEncoding = request.getHeader("Accept-Encoding");
        System.out.println("Accept-Encoding: " + acceptEncoding);

        if (acceptEncoding != null && acceptEncoding.toLowerCase().contains("gzip")) {

            // 如果客户浏览器支持 GZIP 格式, 则使用 GZIP 压缩数据
            GzipResponseWrapper gzipResponse = new GzipResponseWrapper(response);
            chain.doFilter(request, gzipResponse);

            // 输出压缩数据
            gzipResponse.getOutputStream();
            gzipResponse.finishResponse();

        } else {
            // 否则, 不压缩
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }


    @Override
    public void destroy() {
    }
}
